<template>
    <div class="add_goods">
        <header>新增商品</header>
        <div class="contents">
            <div class="base_info">
                <div class="base_title titles">基本信息</div>
                <div class="base_condition">
                    <div class="base_condition_1">
                        <p>所属门店</p>
                        <el-select v-model="value1" placeholder="请选择" style="width:300px;" @change="getGoodsType()">
                            <el-option v-for="item in options1" :key="item.value" :label="item.SHOPNAME" :value="item.SHOPNAME">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="base_condition_2">
                        <p>商品名称</p>
                        <el-input v-model.trim="input1" placeholder="请输入商品名称" style="width:300px;"></el-input>
                    </div>
                    <div class="base_condition_3">
                        <p>所属分类</p>
                        <el-select v-model="value2" placeholder="请选择" style="width:300px;" @change="getTypeId()">
                            <el-option v-for="item in options2" :key="item.value" :label="item.SUBJECT" :value="item.SUBJECT">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div class="base_price">
                    <div class="base_app_price">
                        <p>App售价</p>
                        <el-input v-model.trim="input2" placeholder="支持2位小数，不能为负数" style="width:300px;"></el-input>
                    </div>
                    <div class="base_pad_price">
                        <p>Pad售价</p>
                        <el-input v-model.trim="input3" placeholder="支持2位小数，不能为负数" style="width:300px;"></el-input>
                    </div>
                </div>
            </div>
            <div class="show_status">
                <div class="show_status_title titles">显示状态</div>
                <div class="show_platform">
                    <p>显示平台：</p>
                    <el-checkbox-group v-model="showCheckList">
                        <el-checkbox label="App"></el-checkbox>
                        <el-checkbox label="iPad"></el-checkbox>
                    </el-checkbox-group>
                </div>
            </div>
            <div class="marketing">
                <div class="marketing_title titles">营销策略</div>
                <div class="show_ticket">
                    <p>券策略：</p>
                    <el-checkbox-group v-model="saleCheckList">
                        <el-checkbox label="满减券"></el-checkbox>
                        <el-checkbox label="N元券"></el-checkbox>
                        <el-checkbox label="折扣券"></el-checkbox>
                    </el-checkbox-group>
                </div>
            </div>
            <!-- 上传start -->
            <div class="goods_imgs">
                <div class="goods_title titles">商品图片</div>
                <div class="all_imgs">
                    <div class="upload_img common">
                        <p>上传App封面：</p>
                        <div slot="tip" class="el-upload__tip" style="margin-bottom:10px;">只能上传jpg/png文件，且不超过500kb</div>
                        <div class="up_imgs" style="display:flex;">
                            <img id="showImg" width="94" height="94" src="../../assets/images/market/upload.png" style="cursor:pointer;" alt="" @click.stop='autoClick' />
                            <input type="file" @change="appImgUpdate($event)" style="display:none;" id="upfile" @click.stop='autoClick'> </div>
                    </div>
                    <div class="upload_img common">
                        <p>上传Pad封面：</p>
                        <div slot="tip" class="el-upload__tip" style="margin-bottom:10px;">只能上传jpg/png文件，且不超过500kb</div>
                        <div class="up_imgs" style="display:flex;">
                            <img id="showImg2" width="94" height="94" src="../../assets/images/market/upload.png" style="cursor:pointer;" alt="" @click.stop='autoClick2' />
                            <input type="file" @change="padImgUpdate($event)" style="display:none;" id="upfile2" @click.stop='autoClick2'> </div>
                    </div>
                </div>
            </div>
            <!-- 上传end -->
            <div class="goods_attr">
                <div class="goods_attr_title titles">商品属性</div>
                <div class="goods_attr_info">
                    <div class="goods_all_attr" v-for="(item,index) in goodsAttr" :key="item.id">
                        <p>{{item.number}}</p>
                        <div class="attr_type">
                            <p>属性类型：</p>
                            <el-select v-model="item['value' + index]" placeholder="请选择" style="width:300px;">
                                <el-option v-for="item in options3" :key="item.id" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="attr_name">
                            <p>属性名称：</p>
                            <el-input v-model.trim="item['attrInputName' + index]" placeholder="" style="width:300px;"></el-input>
                        </div>
                        <div class="attr_cprice">
                            <p>属性差价：</p>
                            <el-input v-model.trim="item['attrInputPrice' + index]" placeholder="请输入数字" style="width:300px;"></el-input>
                        </div>
                        <div @click="delGoodsAttr">
                            <img class="remove_goods" src="../../assets/images/market/remove.png" alt="" />
                        </div>
                    </div>
                    <div class="goods_attr_btn">
                        <el-button type="danger" style="background:#e7251a;" @click="addGoodsAttr">新增属性</el-button>
                        <el-button @click="changeAttr(true)">新增属性类型</el-button>
                        <el-input v-if="attrAdd" v-model.trim="attrType" style="width:100px;margin-left:30px;"></el-input>
                        <el-button v-if="attrAdd" @click="changeAttr(false)" style="margin-left:10px;">确定</el-button>
                    </div>
                </div>
            </div>
            <!-- 详情start -->
            <div class="details">
                <div class="details_title titles">详情</div>
                <div class="goods_detail">
                    <div class="goods_detail_title">商品简述</div>
                    <div class="goods_editor">
                        <quill-editor style="height:350px;" ref="myTextEditor" :content="content" :config="editorOption" @change="onEditorChange($event)">
                        </quill-editor>
                    </div>
                </div>
                <div class="goods_detail">
                    <div class="goods_detail_title" style="padding-top:100px;">图文详情</div>
                    <div class="goods_editor">
                        <quill-editor style="height:350px;" ref="myTextEditor2" :content="content2" :config="editorOption2" @change="onEditorChange2($event)">
                        </quill-editor>
                    </div>
                </div>
            </div>
            <!-- 详情end -->
            <div class="buttonss">
                <el-button>取消</el-button>
                <el-button type="danger" style="background:#e7251a;" @click="saveAndAdd">提交</el-button>
            </div>
        </div>
    </div>
</template>

<script>
//参考https://www.npmjs.com/package/vue-quill-editor
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import $ from "jquery";
import { getSelectShop, cafeTypeList, saveCafe } from "@/api/manages";
import axios from "axios";
export default {
    name: "add_goods",
    data() {
        return {
            value1: "", //所属门店
            options1: [],
            input1: "", //商品名称
            value2: "", //所属分类
            typeID: "", //
            options2: [],
            input2: "", //app售价
            input3: "", //pad售价
            fileList: [], //
            fileList2: [], //
            options3: [],
            content: "",
            editorOption: {},
            content2: "",
            editorOption2: {},
            showCheckList: ["App"], //显示状态
            saleCheckList: ["满减券"], //营销策略
            isApp: 0, // app显示状态
            isPad: 0, // pad显示状态
            suppnorcashvol: 0, // 满减券
            suppcashvol: 0, // N元券
            suppdiscashvol: 0, // 折扣券
            appImgUrl: "", // app封面图片
            padImgUrl: "", // pad封面图片
            goodsAttr: [
                {
                    number: 1
                }
            ], // 商品规格
            attrType: "", //属性
            attrAdd: false
        };
    },
    methods: {
        test(file) {
            console.log(123);
        },
        handlePreview(file) {
            console.log(123);
            console.log(file);
        },
        handlePreview2(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        onEditorChange({ editor, html, text }) {
            this.content = html;
        },
        onEditorChange2({ editor, html, text }) {
            this.content2 = html;
        },
        // 获取商品分类下拉列表
        getGoodsType() {
            this.value2 = "";
            // 获取选择的当前门店ID
            this.options1.forEach(item => {
                if (item.SHOPNAME === this.value1) {
                    this.compID = item.COMPID;
                }
            });
            cafeTypeList({
                PAGE_NO: "1",
                PAGE_SIZE: "6",
                COMPID: this.compID
            }).then(res => {
                if (res.data.STATUS_CODE === 1) {
                    this.options2 = res.data.CAFETYPARR;
                }
            });
        },
        autoClick() {
            document.getElementById("upfile").click();
        },
        autoClick2() {
            document.getElementById("upfile2").click();
        },
        appImgUpdate($event) {
            if ($event.target.files.length == 0) {
                return;
            }
            if ($event.target.files[0].size > 512000) {
                this.$alert("文件大小超过限制", "提示", {
                    confirmButtonText: "确定"
                });
                this.appImgUrl = [];
                return;
            }
            if (!/(png)|(jpeg)$/.test($event.target.files[0].type)) {
                this.$alert("文件格式不正确", "提示", {
                    confirmButtonText: "确定"
                });
                this.appImgUrl = [];
                return;
            }
            //图片预览fileReader
            let fr = new FileReader();
            fr.readAsDataURL($event.target.files[0]);
            let _this = this;
            let sImg = document.getElementById("showImg");
            fr.onload = function(evt) {
                sImg.src = evt.target.result;
                _this.appImgUrl = evt.target.result.split(",")[1];
            };
        },
        padImgUpdate($event) {
            if ($event.target.files.length == 0) {
                return;
            }
            if ($event.target.files[0].size > 512000) {
                this.$alert("文件大小超过限制", "提示", {
                    confirmButtonText: "确定"
                });
                this.padImgUrl = [];
                return;
            }
            if (!/(png)|(jpeg)$/.test($event.target.files[0].type)) {
                this.$alert("文件格式不正确", "提示", {
                    confirmButtonText: "确定"
                });
                this.padImgUrl = [];
                return;
            }
            //图片预览fileReader
            let fr = new FileReader();
            fr.readAsDataURL($event.target.files[0]);
            let _this = this;
            let sImg = document.getElementById("showImg2");
            fr.onload = function(evt) {
                sImg.src = evt.target.result;
                _this.padImgUrl = evt.target.result.split(",")[1];
            };
        },
        // 新增属性
        addGoodsAttr() {
            if (this.goodsAttr.length > 4) {
                this.$alert("最多添加5个属性", "提示", {
                    type: "waring"
                });
                return;
            }
            this.goodsAttr.push({
                number: this.goodsAttr.length + 1,
                value: "value" + (this.goodsAttr.length + 1),
                attrInputName: "attrInputName" + (this.goodsAttr.length + 1),
                attrInputPrice: "attrInputPrice" + (this.goodsAttr.length + 1)
            });
        },
        // 删除属性
        delGoodsAttr() {
            if (this.goodsAttr.length === 1) {
                this.$alert("没有属性可以删除", "提示", {
                    type: "waring"
                });
                return;
            }
            this.goodsAttr.pop();
        },
        changeAttr(value) {
            this.attrAdd = value;
            if (this.attrType !== "") {
                this.options3.push(this.attrType);
                this.attrType = "";
            }
        },
        // 获取属性列表方法
        attrList() {
            // 遍历列表取出值
            let attrAry = [];
            this.goodsAttr.forEach((item, index) => {
                attrAry.push({
                    ATTRTYPE: "",
                    ATTRNAME: "",
                    DIFFPRICE: ""
                });
                attrAry[index].ATTRTYPE = item["value" + index];
                attrAry[index].ATTRNAME = item["attrInputName" + index];
                attrAry[index].DIFFPRICE = item["attrInputPrice" + index];
            });

            // 如果有不符合要求的值则返回false
            let flag = true;
            if (attrAry.length === 1 && !attrAry[0].ATTRTYPE) {
                return [];
            }
            attrAry.forEach(item => {
                if (
                    !item.ATTRTYPE ||
                    !item.ATTRNAME ||
                    !/^(\-)?\d+(\.\d{1,2})?$/.test(item.DIFFPRICE)
                ) {
                    flag = false;
                }
            });
            if (flag) {
                return attrAry;
            } else {
                return false;
            }
        },
        // 优惠券状态转换
        coponStatusChange() {
            this.showCheckList.forEach(item => {
                if (/^App/.test(item)) {
                    this.isApp = 1;
                } else {
                    this.isApp = 0;
                }
                if (/^iPad/.test(item)) {
                    this.isPad = 1;
                } else {
                    this.isPad = 0;
                }
            });
            this.saleCheckList.forEach(item => {
                if (/^满减券/.test(item)) {
                    this.suppnorcashvol = 1;
                }
                if (/^N元券/.test(item)) {
                    this.suppcashvol = 1;
                }
                if (/^折扣券/.test(item)) {
                    this.suppdiscashvol = 1;
                }
            });
        },
        getTypeId() {
            // 获取选择的当前商品分类ID
            this.options2.forEach(item => {
                if (item.SUBJECT === this.value2) {
                    this.typeID = item.CAFETYPEID;
                    return;
                }
            });
        },
        // 保存提交商品
        saveAndAdd() {
            // 验证是否有填写
            if (!this.compID) {
                this.$alert("请选择门店", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.input1 === "") {
                this.$alert("请填写商品名称", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.value2 === "") {
                this.$alert("请选择商品分类", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            // 验证价格不能为负数，支持2位以内小数
            if (
                !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(
                    this.input2
                )
            ) {
                this.$alert("请正确填写App售价", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (
                !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(
                    this.input3
                )
            ) {
                this.$alert("请正确填写Pad售价", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.appImgUrl.length === 0) {
                this.$alert("请选择App封面", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.padImgUrl.length === 0) {
                this.$alert("请选择iPad封面", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.attrList() === false) {
                this.$alert("请正确填写的属性", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.content === "") {
                this.$alert("商品简述不能为空", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.content2 === "") {
                this.$alert("商品详情不能为空", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }

            // 显示状态、营销策略状态转换
            this.coponStatusChange();

            var params = {
                COMPID: this.compID, // 店铺ID
                SERVNAME: this.input1, // 商品名称
                SECONDCLASS: this.typeID, // 商品分类
                APPPRICE: this.input2, // App售价
                PADPRICE: this.input3, //Pad售价
                ISAPP: this.isApp, // 是否选择app
                ISPAD: this.isPad, // 是否选择ispad
                SUPPNORCASHVOL: this.suppnorcashvol, // 是否选择满减券
                SUPPCASHVOL: this.suppcashvol, // 是否选择N元券
                SUPPDISCASHVOL: this.suppdiscashvol, // 是否选择折扣券
                SERVSIMPLEDESC: this.content, // 商品简述
                SERVDESC: this.content2, // 商品详情
                APPPHOTOARR: JSON.stringify([
                    {
                        URL: this.appImgUrl,
                        SORTNUM: 1,
                        ISCOVER: 1,
                        SERVPHOTOID: null
                    }
                ]), // App封面图
                PADPHOTOARR: JSON.stringify([
                    {
                        URL: this.padImgUrl,
                        SORTNUM: 1,
                        ISCOVER: 1,
                        SERVPHOTOID: null
                    }
                ]) // App封面图
            };

            // 如果有填写属性则添加
            if (this.attrList()[0] !== undefined) {
                params.ATTRARR = JSON.stringify(this.attrList());
            }
            // 发送请求
            var _this = this
            $.ajax({
                url: window.getIps + "/4SCAFE/Coffee/saveCafe.action",
                type: "post",
                data: params,
                success: function(res) {
                    if (res.STATUS_CODE == 1) {
                        _this.$message({
                            type: "success",
                            message: "添加成功"
                        });
                        setTimeout(()=>{
                            _this.$router.push("/manages/goods");
                        },1000)
                    }
                }
            });
        }
    },
    created() {
    	//离开页面提醒
    	window.onbeforeunload = function(e) {
            var e = window.event || e;
            e.returnValue = ("在新增或编辑时，关闭选项卡将导致数据无法保存");
        }
        // 载入时获取门店下拉列表数据
        getSelectShop({
            LIKESTR: "",
            PAGE_NO: "1",
            PAGE_SIZE: "100"
        }).then(res => {
            if (res.data.STATUS_CODE === 1) {
                this.options1 = res.data.SHOPARR;
            }
        });
    },
    computed: {
        editor() {
            return this.$refs.myTextEditor.quillEditor;
        },
        editor2() {
            return this.$refs.myTextEditor2.quillEditor;
        }
    },
    mounted() {
        //console.log('this is my editor', this.editor)
    },
    components: {
        quillEditor
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.add_goods {
    min-height: 100%;
    background: #f0f2f5;
    padding-bottom: 50px;
    header {
        background: #fff;
        font-size: 22px;
        font-weight: 700;
        padding: 20px;
    }
    .contents {
        .titles {
            height: 55px;
            margin-top: 30px;
            font-size: 20px;
            line-height: 55px;
            padding-left: 30px;
            border-bottom: 1px solid #dcdcdc;
            font-weight: 700;
        }
        .base_info {
            width: 97%;
            background: #fff;
            margin: 0 auto;
            padding-bottom: 40px;
            .base_condition {
                width: 62%;
                display: flex;
                justify-content: space-around;
            }
            .base_price {
                width: 41.5%;
                display: flex;
                justify-content: space-around;
                margin-top: 20px;
            }
        }
        .show_status,
        .marketing,
        .goods_attr {
            width: 97%;
            background: #fff;
            margin: 0 auto;
            margin-top: 30px;
            .show_platform,
            .show_ticket {
                height: 80px;
                display: flex;
                align-items: center;
                padding-left: 30px;
            }
        }
        .goods_imgs {
            width: 97%;
            background: #fff;
            margin: 0 auto;
            margin-top: 30px;
            .all_imgs {
                display: flex;
                padding: 30px;
                .app_img {
                    width: 50%;
                    .app_img_title {
                        margin-bottom: 30px;
                    }
                }
                .pad_img {
                    width: 50%;
                    .pad_img_title {
                        margin-bottom: 30px;
                    }
                }
                .upload_img {
                    width: 50%;
                }
            }
        }
        .goods_attr {
            border: 1px solid #ebebeb;
            .goods_attr_info {
                padding-top: 30px;
                .goods_all_attr {
                    display: flex;
                    justify-content: space-around;
                    align-items: center;
                    > p {
                        border: 1px solid #cdcdcd;
                        padding: 8px;
                    }
                    .attr_type {
                        display: flex;
                        align-items: center;
                    }
                    .attr_name {
                        display: flex;
                        align-items: center;
                    }
                    .attr_cprice {
                        display: flex;
                        align-items: center;
                    }
                    .remove_goods {
                        width: 32px;
                        height: 32px;
                        cursor: pointer;
                    }
                }
                .goods_attr_btn {
                    display: flex;
                    padding: 30px 0 30px 50px;
                }
            }
        }
        .details {
            width: 97%;
            background: #fff;
            margin: 0 auto;
            margin-top: 30px;
            border: 1px solid #ebebeb;
            .goods_detail {
                .goods_detail_title {
                    padding: 30px;
                }
            }
            .img_detail {
                margin-top: 30px;
                .img_detail_title {
                    padding: 30px;
                }
            }
        }
        .buttonss {
            margin: 90px 50px 40px 0;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>
